package com.example.airole.tts.service.impl;

import com.example.airole.tts.entity.TTSRequest;
import com.example.airole.tts.entity.TTSResponse;
import com.example.airole.tts.service.TTSService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 百度TTS服务实现
 */
@Slf4j
@Service("baiduTTSService")
public class BaiduTTSService implements TTSService {
    
    @Value("${airole.tts.baidu.app-id:}")
    private String appId;
    
    @Value("${airole.tts.baidu.api-key:}")
    private String apiKey;
    
    @Value("${airole.tts.baidu.secret-key:}")
    private String secretKey;
    
    @Value("${airole.tts.baidu.enabled:true}")
    private boolean enabled;
    
    private final RestTemplate restTemplate = new RestTemplate();
    private final ExecutorService executorService = Executors.newFixedThreadPool(5);
    private final ConcurrentHashMap<String, TTSResponse> asyncResults = new ConcurrentHashMap<>();
    
    private static final String TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token";
    private static final String TTS_URL = "https://tsn.baidu.com/text2audio";
    
    @Override
    public TTSResponse synthesize(TTSRequest request) {
        if (!enabled) {
            return TTSResponse.builder()
                    .success(false)
                    .errorMessage("百度TTS服务未启用")
                    .build();
        }
        
        try {
            long startTime = System.currentTimeMillis();
            
            // 获取访问令牌
            String accessToken = getAccessToken();
            if (accessToken == null) {
                return TTSResponse.builder()
                        .success(false)
                        .errorMessage("获取访问令牌失败")
                        .build();
            }
            
            // 构建请求参数
            Map<String, String> params = buildRequestParams(request, accessToken);
            
            // 发送TTS请求
            ResponseEntity<byte[]> response = restTemplate.postForEntity(TTS_URL, params, byte[].class);
            
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                long processingTime = System.currentTimeMillis() - startTime;
                
                // 将音频数据转换为Base64
                String audioData = Base64.getEncoder().encodeToString(response.getBody());
                
                return TTSResponse.builder()
                        .success(true)
                        .audioData(audioData)
                        .audioFormat("mp3")
                        .voiceUsed(request.getVoice())
                        .languageUsed(request.getLanguage())
                        .processingTime(processingTime)
                        .build();
            } else {
                return TTSResponse.builder()
                        .success(false)
                        .errorMessage("TTS合成失败，HTTP状态码: " + response.getStatusCode())
                        .build();
            }
            
        } catch (Exception e) {
            log.error("百度TTS合成异常", e);
            return TTSResponse.builder()
                    .success(false)
                    .errorMessage("TTS合成失败: " + e.getMessage())
                    .build();
        }
    }
    
    @Override
    public String synthesizeAsync(TTSRequest request) {
        String taskId = "tts_task_" + System.currentTimeMillis() + "_" + Thread.currentThread().getId();
        
        executorService.submit(() -> {
            try {
                TTSResponse response = synthesize(request);
                asyncResults.put(taskId, response);
            } catch (Exception e) {
                log.error("异步TTS合成异常", e);
                asyncResults.put(taskId, TTSResponse.builder()
                        .success(false)
                        .errorMessage("异步TTS合成失败: " + e.getMessage())
                        .build());
            }
        });
        
        return taskId;
    }
    
    @Override
    public TTSResponse getAsyncResult(String taskId) {
        return asyncResults.get(taskId);
    }
    
    @Override
    public boolean isServiceAvailable() {
        if (!enabled) {
            return false;
        }
        
        return appId != null && !appId.isEmpty() && 
               apiKey != null && !apiKey.isEmpty() && 
               secretKey != null && !secretKey.isEmpty();
    }
    
    @Override
    public String[] getSupportedVoices() {
        return new String[]{"0", "1", "3", "4", "5", "103", "106", "110", "111"};
    }
    
    @Override
    public String[] getSupportedLanguages() {
        return new String[]{"zh", "en"};
    }
    
    @Override
    public String[] getSupportedFormats() {
        return new String[]{"mp3", "wav"};
    }
    
    /**
     * 获取访问令牌
     */
    private String getAccessToken() {
        try {
            String url = TOKEN_URL + "?grant_type=client_credentials&client_id=" + 
                        URLEncoder.encode(apiKey, StandardCharsets.UTF_8) + 
                        "&client_secret=" + URLEncoder.encode(secretKey, StandardCharsets.UTF_8);
            
            ResponseEntity<Map> response = restTemplate.getForEntity(url, Map.class);
            
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                Map<String, Object> body = response.getBody();
                return (String) body.get("access_token");
            }
            
            return null;
        } catch (Exception e) {
            log.error("获取百度访问令牌失败", e);
            return null;
        }
    }
    
    /**
     * 构建请求参数
     */
    private Map<String, String> buildRequestParams(TTSRequest request, String accessToken) {
        Map<String, String> params = new HashMap<>();
        params.put("tex", request.getText());
        params.put("tok", accessToken);
        params.put("cuid", appId);
        params.put("ctp", "1");
        params.put("lan", request.getLanguage() != null ? request.getLanguage() : "zh");
        params.put("spd", String.valueOf(request.getSpeed() != null ? request.getSpeed() : 5));
        params.put("pit", "5");
        params.put("vol", "5");
        params.put("per", request.getVoice() != null ? request.getVoice() : "0");
        params.put("aue", "3"); // 输出格式：3为mp3
        return params;
    }
}